﻿// ***********************************************************************
// Assembly         : Admin.Framework.Core.Repository
// Author           : xwltz
// Created          : 2019-05-25
//
// Last Modified By : xwltz
// Last Modified On : 2019-05-25
// ***********************************************************************
// <summary>
//  数据库上下文对象
// </summary>
// ***********************************************************************

using SqlSugar;

namespace Admin.Framework.Core.Repository
{
    public class DataBaseContext
    {
        /// <summary>
        /// 注意：不能写成静态的，不能写成静态的
        /// 用来处理事务多表查询和复杂的操作
        /// </summary>
        public SqlSugarClient Db;

        /// <summary>
        /// 数据库链接字符串
        /// </summary>
        public string ConnectionString = "server=192.168.11.5;uid=sa;pwd=ok;database=test";

        /// <summary>
        /// 初始化数据库对象
        /// </summary>
        public DataBaseContext()
        {
            Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = ConnectionString,
                DbType = DbType.SqlServer,
                InitKeyType = InitKeyType.Attribute, // 从特性读取主键和自增列信息
                IsAutoCloseConnection = true, // 开启自动释放模式和EF原理一样我就不多解释了

                #region 自定义实体特性
                //ConfigureExternalServices=new ConfigureExternalServices() // 自定义实体特性
                //{
                //    EntityService = (property, column) => {
                //        if (property.Name == "xxx") { // 根据列名
                //            column.IsIgnore = true;
                //        }
                //        var attributes = property.GetCustomAttributes(true);
                //        if (attributes.Any(it => it is KeyAttribute)) // 根据自定义属性
                //        {
                //            column.IsPrimarykey = true;
                //        }
                //    },
                //    EntityNameService = (type, entity) => {
                //        var attributes = type.GetCustomAttributes(true);
                //        if (attributes.Any(it => it is TableAttribute))
                //        {
                //            entity.DbTableName = (attributes.First(it => it is TableAttribute) as TableAttribute)?.Name;
                //        }
                //    }
                //}
                #endregion
            });

            #region 调式代码 用来打印SQL 
            //Db.Aop.OnLogExecuting = (sql, pars) =>
            //{
            //    Console.WriteLine(sql + "\r\n" + Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
            //    Console.WriteLine();
            //};
            #endregion
        }

        /// <summary>
        /// 释放数据库对象
        /// </summary>
        ~DataBaseContext()
        {
            Db.Dispose();
        }
    }
}
